import userService from '@/services/user-service';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import { Button, Input, Modal, Space, Table, message } from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';

const InvitationManagement: React.FC = () => {
  const [data, setData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchValue, setSearchValue] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [creatorEmail, setCreatorEmail] = useState('');

  // 获取邀请码列表
  const fetchInvitations = async (params: any = {}) => {
    setLoading(true);
    try {
      const res = await userService.listInvitation({
        page: params.current || pagination.current,
        per_page: params.pageSize || pagination.pageSize,
        search: searchValue,
      });
      const result = res.data;
      setData(result.data.items);
      setPagination({
        ...pagination,
        total: result.data.total,
        current: params.current || pagination.current,
      });
    } catch (error) {
      message.error('获取邀请码列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 创建邀请码
  const handleCreate = async () => {
    if (!creatorEmail) {
      message.warning('请输入创建者邮箱');
      return;
    }

    try {
      await userService.createInvitation({ creator_email: creatorEmail });
      message.success('邀请码创建成功');
      setIsModalVisible(false);
      setCreatorEmail('');
      fetchInvitations();
    } catch (error) {
      message.error('创建邀请码失败');
    }
  };

  // 作废邀请码
  const handleRevoke = async (id: number) => {
    Modal.confirm({
      title: '确认作废邀请码?',
      content: '此操作不可撤销',
      onOk: async () => {
        try {
          await userService.revokeInvitation({ code_id: id });
          message.success('邀请码已作废');
          fetchInvitations();
        } catch (error) {
          message.error('作废邀请码失败');
        }
      },
    });
  };

  // 表格列配置
  const columns = [
    {
      title: '邀请码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '创建者',
      dataIndex: 'creator_email',
      key: 'creator_email',
    },
    {
      title: '使用者',
      dataIndex: 'user_email',
      key: 'user_email',
      render: (text: string) => text || '未使用',
    },
    {
      title: '状态',
      dataIndex: 'is_valid',
      key: 'is_valid',
      render: (valid: boolean) => (
        <span style={{ color: valid ? 'green' : 'red' }}>
          {valid ? '有效' : '已使用/作废'}
        </span>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      render: (time: number) => dayjs(time).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space size="middle">
          {record.is_valid && (
            <Button danger onClick={() => handleRevoke(record.id)}>
              作废
            </Button>
          )}
        </Space>
      ),
    },
  ];

  // 初始化加载
  useEffect(() => {
    fetchInvitations();
  }, []);

  return (
    <div className="invitation-management">
      <div style={{ marginBottom: 16 }}>
        <Space>
          <Input
            placeholder="搜索邀请码或邮箱"
            prefix={<SearchOutlined />}
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
            style={{ width: 300 }}
            allowClear
          />
          <Button
            type="primary"
            onClick={() => fetchInvitations({ current: 1 })}
          >
            搜索
          </Button>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setIsModalVisible(true)}
          >
            生成邀请码
          </Button>
        </Space>
      </div>

      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          onChange: (page, pageSize) => {
            fetchInvitations({ current: page, pageSize });
          },
        }}
      />

      <Modal
        title="生成新邀请码"
        visible={isModalVisible}
        onOk={handleCreate}
        onCancel={() => {
          setIsModalVisible(false);
          setCreatorEmail('');
        }}
      >
        <Input
          placeholder="请输入创建者邮箱"
          value={creatorEmail}
          onChange={(e) => setCreatorEmail(e.target.value)}
        />
      </Modal>
    </div>
  );
};

export default InvitationManagement;
